package com.smart.business.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.smart.aop.log.LogType;
import com.smart.aop.log.SaveLog;
import com.smart.aop.permission.HasPermission;
import com.smart.business.service.CompanyServiceImpl;
import com.smart.common.annotation.PermissionCheck;
import com.smart.common.utils.DateUtil;
import com.smart.common.utils.ThreadLocalUtil;
import com.smart.entity.business.CompanyEntity;
import com.smart.entity.business.PointLocationEntity;
import com.smart.model.excel.annotation.ExcelField;
import com.smart.model.response.r.Result;
import com.smart.model.response.r.ResultCode;
import com.smart.model.response.r.ResultWrapper;
import com.smart.service.business.CompanyService;
import com.smart.tools.excel.ExcelExport;
import com.smart.tools.excel.ExcelImport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 公司表 Controller
 *
 * @author wf
 * @since 2025-06-11 13:15:12
 */
@Slf4j
@RestController
@RequestMapping("/business/company")
public class CompanyController {
    @Autowired
    CompanyService companyService;
    @Autowired
    ResultWrapper resultWrapper;

    /**
     * 列表
     *
     * @param companyEntity 公司表bean
     * @return String
     */
    @GetMapping("/page")
    public String page(CompanyEntity companyEntity) {
        return Result.data(companyService.findPage(companyEntity));
    }

    /**
     * 列表（不分页）
     *
     * @param companyEntity 公司表bean
     * @return String
     */
    @GetMapping("/list")
    public String list(CompanyEntity companyEntity) {
        return Result.data(companyService.findList(companyEntity));
    }

    /**
     * 信息
     *
     * @param id 主键ID
     * @return String
     */
    @GetMapping("/get")
    public String get(@RequestParam String id) {
        CompanyEntity result = companyService.get(id);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 保存
     *
     * @param companyEntity 公司表bean
     * @return String
     */
    @HasPermission("company:add")
    @PostMapping("/save")
    @SaveLog(module = "公司表管理" , type = LogType.ADD)
    public String save(@RequestBody CompanyEntity companyEntity) {
        CompanyEntity result = companyService.saveEntity(companyEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 修改
     *
     * @param companyEntity 公司表bean
     * @return String
     */
    @HasPermission("company:update")
    @PostMapping("/update")
    @SaveLog(module = "公司表管理" , type = LogType.UPDATE)
    public String update(@RequestBody CompanyEntity companyEntity) {
        CompanyEntity result = companyService.updateEntity(companyEntity);
        return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }

    /**
     * 删除
     *
     * @param companyEntity 公司表bean
     * @return String
     */
    @HasPermission("company:delete")
    @PostMapping("/delete")
    @SaveLog(module = "公司表管理" , type = LogType.DELETE)
    public String delete(@RequestBody CompanyEntity companyEntity) {
        return Result.status(companyService.delete(companyEntity));
    }

    /**
     * 导出
     *
     * @param companyEntity 公司表bean
     * @param response 响应
     */
    @HasPermission("company:export")
    @PostMapping(value = "/export")
    public void exportData(@RequestBody CompanyEntity companyEntity, HttpServletResponse response) {
        List<CompanyEntity> list = resultWrapper.setListIdentityInfo(companyService.findList(companyEntity), CompanyEntity.class);
        String fileName = "公司表数据" + DateUtil.getDate("yyyyMMddHHmmss") + ".xlsx";
        try (ExcelExport export = new ExcelExport("公司表数据", CompanyEntity.class)) {
            export.setDataList(list).write(response, fileName);
        }
    }

    /**
     * 导入
     *
     * @param request 请求
     */
    @HasPermission("company:import")
    @PostMapping(value = "/import")
    public String importData(MultipartHttpServletRequest request) {
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        List<MultipartFile> files = multiFileMap.get("files");
        try (ExcelImport excelImport = new ExcelImport(files.get(0), 2, 0)) {
            List<CompanyEntity> dataList = excelImport.getDataList(CompanyEntity.class);
            return Result.status(companyService.saveBatch(dataList));
        } catch (Exception e) {
            return Result.fail("导入失败！");
        }
    }

    /**
     * 下载导入模板
     *
     * @param response 响应
     */
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入公司表模板.xlsx";
        try (ExcelExport export = new ExcelExport("公司表数据", CompanyEntity.class, null, ExcelField.Type.IMPORT)) {
            export.write(response, fileName);
        }
    }
    @PermissionCheck
    @GetMapping("/companyNames")
    public String getCompanyNames() {
        List<String> result = ThreadLocalUtil.getPermissionResult();
        return Result.data(result);
    }
    @PermissionCheck
    @GetMapping("/companyByPointData")
    public String getCompanyByPointData() {
            Map<String, Object> result = companyService.getCompanyAndPointData();
            return result != null ? Result.data(result) : Result.fail(ResultCode.FAIL);
    }



    /**
     * 获取公司详情 权限：管理员，服务商公司列表
     * @param current 当前页
     * @param size 每页数量
     * @return String
     */
    @PermissionCheck
    @GetMapping("/companyDetails")
    public String  getCompanyList( @RequestParam(defaultValue = "1") int current,
                                   @RequestParam(defaultValue = "10") int size){

        try {
            Page<CompanyEntity> result = companyService.getCompanyDetails(current, size);
            return Result.data(result);
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        }
    }
    /**
     * 根据权限中存储的数据得到公司及层级点位
     * @return String
     *
     */
    @PermissionCheck
    @GetMapping("/getCurrentDict")
    public String getCurrentDict(@RequestParam(required = false) String meterTypeId) {
        return Result.data(companyService.getCurrentDict(meterTypeId));
    }

    /**
     * 获取不同能源类型的协议解析方式
     * @return String
     */
    @GetMapping("/getProtocol")
    public String getProtocol() {
        return Result.data(companyService.getProtocol());
    }

}
